<template>
  <div>
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :before-close="close"
    >
      <div>
        <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px">
          <el-form-item required label="旧密码" prop="oldPass">
            <el-input v-model="ruleForm.oldPass" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item required label="新密码" prop="pass">
            <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item required label="确认密码" prop="checkPass">
            <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <l-button auto-loading type="primary" @click="save">确 定</l-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { updatePassword } from '@/api/modules/system/sysUserApi'
import LButton from '@/components/loadingButton/LButton'

export default {
  name: 'UpdatePassword',
  components: {
    LButton
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      ruleForm: {
        oldPass: '',
        pass: '',
        checkPass: ''
      },
      rules: {
        oldPass: [{ required: true, trigger: 'blur', message: '请输入旧密码' }],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    open() {
      console.log('open')
      this.dialogVisible = true
    },
    close() {
      this.dialogVisible = false
    },
    save(next) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          updatePassword({
            oldPassword: this.ruleForm.oldPass,
            newPassword: this.ruleForm.pass
          }).then(res => {
            this.$message.success('修改成功')
            this.close()
          }).finally(() => {
            next()
          })
        } else {
          next()
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
